/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.dbdir.core;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.h2.tools.RunScript;

/**
 *
 * @author thotheolh
 */
public class AutoSetup {

    Connection conn = null;
    boolean table_admin_exist = false;
    boolean table_databaseinfo_exist = false;
    boolean table_acl_exist = false;
    boolean table_user_exist = false;
    private Logger logger;

    public AutoSetup(Logger logger, Connection connection) {
        this.logger = logger;
        if (connection != null) {
            this.conn = connection;
        }else{
            System.out.println("Connection is null !");
        }
    }

    public int isTablesExist() throws SQLException {//Checks if dbDir database exists and what status it exist in.
        int status = -1; //0 - no table or fragments of table, 1 - full fledge database, -1 - error
        try {
            PreparedStatement pstmt = conn.prepareStatement("SHOW TABLES");
            ResultSet rs = pstmt.executeQuery();
                while (rs.next()) {
                    String tableName = rs.getString("TABLE_NAME");
//                    System.out.println("Found Table: " + tableName);
                    checkTables(tableName);
                }
                if ((table_admin_exist == true) && (table_databaseinfo_exist == true) && (table_acl_exist == true) && (table_user_exist == true)) {
                    return status = 1;
                } else if ((table_admin_exist != true) && (table_databaseinfo_exist != true) && (table_acl_exist != true) && (table_user_exist != true)) {
                    return status = 0;
                } else {
                    return status = 0;
                }
        } catch (SQLException ex) {
            logger.log(2, ex.getMessage());
        }
        return status;
    }

    public void setup(String filepath) {//Setup dbDir database.
        logger.log(0, "Autosetup started");
        File file = new File(filepath);
        if (file.exists()) {
            try {
                System.out.println("Setup script @ " + file.getAbsolutePath());
                RunScript.execute(conn, new FileReader(file.getAbsoluteFile()));
//                String statement = "RUNSCRIPT FROM '" + file.getAbsolutePath() + "'";                
//                PreparedStatement pstmt = conn.prepareStatement(statement);
//                int exNum = pstmt.executeUpdate();
//                if (exNum >= 1) {
//                    System.out.println("Setup: " + exNum + " - Setup successfully completed !");
//                    conn.commit();
//                }
                
                System.out.println("Setup done...");
                logger.log(0, "AutoSetup done");
            } catch (FileNotFoundException ex) {
                logger.log(2, ex.getMessage());
            } catch (SQLException ex) {
                logger.log(2, ex.getMessage());
            }
        } else {
            System.out.println("(!): Can't find setup file.");
            logger.log(3,"Can't find setup file");
        }

    }

//    public void clean() {//Deletes all existing dbDir database. // ! Not a workable solution !
//        System.out.println("Cleaning up...");
//        try {
//            String statement = "DROP ALL OBJECTS DELETE FILES";
//            PreparedStatement pstmt = conn.prepareStatement(statement);
//            int exNum = pstmt.executeUpdate();
//            if (exNum >= 1) {
//                System.out.println("Clean: " + exNum + " - Cleaning up done...");
//            } else {
//                System.out.println("Clean: " + exNum + " - " +
//                        "Nothing to clean...");
//            }
//        } catch (SQLException ex) {
//            Logger.getLogger(AutoSetup.class.getName()).log(Level.SEVERE, null, ex);
//        }
//    }

    public void init(String setupFilePath) {
        try {
            int dbStats = this.isTablesExist();
            if (dbStats == 0) {
                System.out.println("Attempting to adjust database...");
                logger.log(1,"Database needs adjustments. Attempting to adjust");
                this.setup(setupFilePath);
                if (this.isTablesExist() == 1) {
                    System.out.println("System Database OK !");
                    logger.log(0, "System Database OK !");
                } else {
                    System.out.println("(!): Failed to adjust system database properly...");
                    logger.log(2, "Failed to adjust system database properly");
                }
            } else if (dbStats == 1) {
                System.out.println("System Database OK !");
                logger.log(0, "System Database OK !");
            } else {
                System.out.println("(!): System Database have some ERRORS ! Trying to go on despite error(s)...");
                logger.log(2,"System Database have some ERRORS ! Trying to go on despite error(s)");
            }
        } catch (SQLException ex) {
            logger.log(2, ex.getMessage());
        }
    }

    public void checkTables(String tableName) {
        if (tableName.equalsIgnoreCase("ADMIN")) {
            table_admin_exist = true;
        }
        if (tableName.equalsIgnoreCase("DATABASEINFO")) {
            table_databaseinfo_exist = true;
        }
        if (tableName.equalsIgnoreCase("ACL")) {
            table_acl_exist = true;
        }
        if (tableName.equalsIgnoreCase("USER")) {
            table_user_exist = true;
        }

    }
}
